import { fileURLToPath } from "node:url";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import UnoCSS from "unocss/vite";
import AutoImport from "unplugin-auto-import/vite";
// vite.config.js
import { defineConfig } from "vite";
import vueDevTools from "vite-plugin-vue-devtools";
import path from "path";
import "reflect-metadata";

import { createAdvanceApi } from "../../dist/index";

import { UserSchema } from "./src/entities/UserSchema";
// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
    UnoCSS(),
    createAdvanceApi({
      prefix: "/api",
      // 配置 Socket.IO
      database: {
        type: "typeorm",
        options: {
          type: "mysql", // 或 "postgres", "sqlite", 等
          host: "localhost",
          port: 3306,
          username: "root",
          password: "123456",
          database: "test",
          synchronize: true,
          logging: true,
          entities: [UserSchema],
        },
      },
      socket: {
        enable: true,
        options: {
          cors: { origin: "*" },
        },
      },
      // 扫描路由
      routerScan: {
        paths: ["server"],
        pattern: "**/*.router.js",
      },
      // 设置 Socket.IO 事件处理
      setup: (utils) => {
        const { io, db } = utils;

        if (io) {
          io.on("connection", (socket) => {
            console.log("用户连接:", socket.id);
          });
        }

        return [
          {
            type: "direct",
            base: "",
            routes: (router) => {
              router.get("/users", async (req, res) => {
                try {
                  const userRepository = utils.db.getRepository(UserSchema);
                  const users = await userRepository.find();
                  res.success(users);
                } catch (error) {
                  res.error(error.message);
                }
              });

              // 添加用户
              router.post("/users", async (req, res) => {
                try {
                  const userRepository = utils.db.getRepository(UserSchema);
                  const user = userRepository.create(req.body);
                  const result = await userRepository.save(user);
                  res.success(result);
                } catch (error) {
                  res.error(error.message);
                }
              });

              // 获取单个用户
              router.get("/users/:id", async (req, res) => {
                try {
                  const userRepository = utils.db.getRepository(UserSchema);
                  const user = await userRepository.findOne({
                    where: { id: parseInt(req.params.id) },
                  });

                  if (!user) {
                    return res.error("用户不存在", 404);
                  }

                  res.success(user);
                } catch (error) {
                  res.error(error.message);
                }
              });

              // 更新用户
              router.put("/users/:id", async (req, res) => {
                try {
                  const userRepository = utils.db.getRepository(UserSchema);
                  const user = await userRepository.findOne({
                    where: { id: parseInt(req.params.id) },
                  });

                  if (!user) {
                    return res.error("用户不存在", 404);
                  }

                  userRepository.merge(user, req.body);
                  const result = await userRepository.save(user);
                  res.success(result);
                } catch (error) {
                  res.error(error.message);
                }
              });

              // 删除用户
              router.delete("/users/:id", async (req, res) => {
                try {
                  const userRepository = utils.db.getRepository(UserSchema);
                  const result = await userRepository.delete(
                    parseInt(req.params.id)
                  );

                  if (result.affected === 0) {
                    return res.error("用户不存在", 404);
                  }

                  res.success({ message: "用户已删除" });
                } catch (error) {
                  res.error(error.message);
                }
              });
            },
          },
        ];
      },
    }),
    AutoImport({
      imports: ["vue"],
      dts: "src/type/auto-imports.d.ts",
      dirs: ["./src/composables"],
      eslintrc: {
        enabled: true,
        filepath: "./.eslintrc-auto-import.json",
      },
    }),
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});
